package views.components;

import java.util.ArrayList;
import utils.MessageUtils;
import utils.ReflectionUtils;

import com.vaadin.addon.jpacontainer.JPAContainer;
import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.data.fieldgroup.FieldGroup;
import com.vaadin.data.fieldgroup.FieldGroup.CommitException;
import com.vaadin.data.util.BeanItem;
import com.vaadin.data.validator.BeanValidator;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Field;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Notification;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;

import dao.interfaces.IBase;

@SuppressWarnings("serial")
/**
 * Clase per a inserir un nou registre en un container de vaadin
 *
 */
public class NuevoRegistro extends Window implements Button.ClickListener {

	private VerticalLayout root;
	private Button btGuardar, btCancelar;
	private FieldGroup fieldGroup;
	private JPAContainer<IBase> jpaContainer;
	private BeanItem<IBase> beanItem;

	public NuevoRegistro(Class<IBase> myClass, JPAContainer<IBase> jpaContainer)
			throws InstantiationException, IllegalAccessException {
		this.jpaContainer = jpaContainer;

		root = new VerticalLayout();
		btGuardar = new Button(MessageUtils.getI18n("guardar"), this);
		btCancelar = new Button(MessageUtils.getI18n("cancelar"), this);
		beanItem = new BeanItem<IBase>(myClass.newInstance());
		fieldGroup = new FieldGroup(beanItem);
		fieldGroup.setItemDataSource(beanItem);

		Field<?> field;
		BeanValidator beanValidator;

		// les propietats visibles

		ArrayList<String> viewFields = ReflectionUtils
				.getViewFieldsSenseIdDateUser(myClass, "record");

		// Si un camp es ManyToOne, OneToMany o enum te tractament especial
		// si no ho es el generem en el fieldgroup

		for (String viewField : viewFields) {

			field = ReflectionUtils.construirSelector(viewField, myClass);

			if (field != null) {
				fieldGroup.bind(field, viewField);

			} else {

				field = fieldGroup.buildAndBind(viewField);

				if (field instanceof TextField)
					((TextField) field).setNullRepresentation("");

			}

			beanValidator = new BeanValidator(myClass, viewField);
			if (beanValidator != null)
				field.addValidator(beanValidator);
			
			field.setWidth("210px");
			field.setCaption(MessageUtils.getI18n(field.getCaption()));
			root.addComponent(field);

		}

		// agrege els botons
		HorizontalLayout hlBotons = new HorizontalLayout(btGuardar, btCancelar);
		hlBotons.setMargin(true);
		hlBotons.setSpacing(true);
		root.setMargin(true);
		root.setSpacing(true);
		setContent(root);
		
		String i18nClase = MessageUtils.getI18n(myClass.getSimpleName());
		String i18nNew = MessageUtils.getI18n("formulari_nuevo");		
		setCaption(i18nNew+i18nClase);
		root.addComponent(hlBotons);

	}

	@Override
	public void buttonClick(ClickEvent event) {
		// si el boto es guardar
		if (event.getButton() == btGuardar) {
			guardar();
		} else {
			close();
		}
	}

	private void guardar() {
		try {

			fieldGroup.commit();
			IBase bean = beanItem.getBean();
			jpaContainer.addEntity(bean);
			UI.getCurrent().getContent().markAsDirtyRecursive();
			close();
		} catch (CommitException e) {
			e.printStackTrace();
			Notification.show(MessageUtils.getI18n("exception_commit"));
		}catch (InvalidValueException  e) {
			e.printStackTrace();
			Notification.show(MessageUtils.getI18n("exception_invalid_value"));
		}
	}

}
